package com.hnust.root.web.aspect;

import com.hnust.root.web.annotation.SysLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;

/**
 * @Author zhusir
 * @Date 2019/2/10
 * @Desc
 */
@Aspect
@Configuration
public class ControllerAspect {

    /**
     * 自定义切面，目前是所有ccontroller
     */
    @Pointcut("execution(* com.hnust.root.web.controller..*(..))  ")
    public void aspect() {
    }

    @Around(value = "aspect()")
    public Object handleAspect(ProceedingJoinPoint pjp) throws Throwable {
        Method method = currentMethod(pjp,pjp.getSignature().getName());

        AspectApiImpl aspectApi = new AspectApiImpl();
        //如果有sysLog注解，则执行记录日志操作
        if (method.isAnnotationPresent(SysLog.class)) {
            return new LogAspect(aspectApi).doHandlerAspect(pjp, method);
        }
        return  pjp.proceed(pjp.getArgs());
    }

    /**
     * 获取目标类的所有方法，找到当前要执行的方法
     */
    private Method currentMethod (ProceedingJoinPoint joinPoint , String methodName ) {
        Method[] methods      = joinPoint.getTarget().getClass().getMethods();
        Method   resultMethod = null;
        for ( Method method : methods ) {
            if ( method.getName().equals( methodName ) ) {
                resultMethod = method;
                break;
            }
        }
        return resultMethod;
    }
}
